// use std::net::TcpListener;
use std::{
    fs,
    io::{
        prelude::*, BufReader
    },
    net::{
        TcpListener,
        TcpStream
    },
    thread,
    time::Duration,
};


fn main() {
    
    // 监听地址
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();

    // incoming 会返回一个迭代器，它每一次迭代都会返回一个新的连接 stream(客户端发起，web服务器监听接收)
    //，因此，接下来要做的就是从 stream 中读取数据，然后返回处理后的结果。
    for stream in listener.incoming() {
        let stream = stream.unwrap();
        println!("Connection established!");

        handle_connection(stream)
    }
}

// 处理从客户端传过来的数据
fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);

    let http_request: Vec<_> = buf_reader.lines()
    .map(|result| result.unwrap())
    .take_while(|line| !line.is_empty())
    .collect();

    println!("Request: {:#?}", http_request);

    // let response = "HTTP/1.1 200 OK\r\n\r\n";
    // stream.write(response.as_bytes()).unwrap();
    
    // do something.
    thread::sleep(Duration::from_secs(5));

    let status_line = "HTTP/1.1 200 OK";
    let contents = fs::read_to_string("index.html").unwrap();
    let length = contents.len();
    let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

    stream.write(response.as_bytes()).unwrap();
}


